<template>
  <a-modal
    v-model:visible="dataModel.visible"
    :mask-closable="false"
    :ok-loading="loading"
    :on-before-ok="handleOk"
    @cancel="handleCancel"
  >
    <template #title>
      {{ dataModel.title }}
    </template>
    <div>
      <a-form
        ref="deptModalForm"
        :model="formData"
        :disabled="dataModel.disabled"
        :style="{width:'100%'}">
        <a-form-item
          field="name"
          label="名称"
          :rules="[{required: true, message:'请输入组织机构名'}]">
          <a-input v-model="formData.name" placeholder="请输入组织机构名..." allow-clear />
        </a-form-item>
        <a-form-item
          field="code"
          label="编码"
          :rules="[{required: true, message:'请输入组织机构编码'}]">
          <a-input v-model="formData.code" placeholder="请输入组织机构编码..." allow-clear />
        </a-form-item>
        <a-form-item
          field="order"
          label="排序">
          <a-input-number v-model="formData.order" placeholder="请输入排序..." allow-clear />
        </a-form-item>
        <a-form-item
          field="parentId"
          label="上级项"
          :rules="[{required: true, message:'请选择上级项'}]">
          <a-tree-select
            v-model="formData.parentId"
            :allow-clear="true"
            :data="depts"
            :field-names="{
                key: 'id',
                title: 'name'
            }"
            tree-check-strictly
            placeholder="请选择上级组织机构..."
          ></a-tree-select>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref } from "vue";
import useDataModel from "@/hooks/data-model";
import useLoading from "@/hooks/loading";
import { Operation } from "@/types/global";
import { DeptDto, DeptVo } from "@/types/modules/system";
import { create, findById, listTree, update } from "@/api/modules/system/dept";
import { ValidatedError } from "@arco-design/web-vue/es/form/interface";
import { disableNode } from "@/utils/tree-utils";

const defaultFormData = (): DeptDto => ({
  parentId: 0
})

const deptModalForm = ref<any>(null)
const depts = ref<DeptVo[]>([])
const formData = ref<DeptDto>(defaultFormData())
const { dataModel, openModel, closeModel } = useDataModel()
const { setLoading, loading } = useLoading()
const emit = defineEmits(["refresh"]);

const createHandle = async () => {
  depts.value = [{id: 0, name: '无上级项', }, ...((await listTree()).data || [])]
  openModel('添加组织机构信息', false, true, Operation.CREATE)
}

const updateHandle = async (id: number) => {
  const { data }  = await findById(id)
  depts.value = [{id: 0, name: '无上级项', }, ...((await listTree()).data || [])]
  disableNode(id, depts.value)
  formData.value = {
    ...data
  }
  openModel('编辑组织机构信息', false, true, Operation.UPDATE)
}

const previewHandle = async (id: number) => {
  const { data }  = await findById(id)
  depts.value = [{id: 0, name: '无上级项', }, ...((await listTree()).data || [])]
  formData.value = {
    ...data
  }
  openModel('预览组织机构信息', true, false, Operation.PREVIEW)
}

const handleCancel = () => {
  closeModel()
  setLoading(false)
  formData.value = defaultFormData()
}

const handleOk = async (done: (closed: boolean) => void) => {
  if (dataModel.submit) {
    setLoading(true);
    if (deptModalForm.value) {
      await deptModalForm.value?.validate(async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          if (dataModel.type === Operation.CREATE) {
            await create(formData.value)
          } else if (dataModel.type === Operation.UPDATE) {
            await update(formData.value)
          }
          setLoading(false)
          done(true)
          handleCancel()
          emit("refresh");
        } else {
          done(false)
        }
      })
    }
  } else {
    handleCancel()
    done(true)
  }
}

defineExpose({ createHandle, updateHandle, previewHandle })
</script>

<script lang="ts">
export default {
  name: "DeptModal"
};
</script>

<style scoped>

</style>
